<?php
namespace app\command;

use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\facade\Cache;
use swoole_process;
use Redis;



class Hello extends Command
{

    private static $redis = null;

    /**
     * 重写configure
     * {@inheritdoc}
     */
    protected function configure()
    {
   /*     $log = file_get_contents(dirname(__FILE__) . '/run_times   .log');
        $log = explode("\n",trim($log));
        foreach($log as &$tmp) {
            $tmp = explode(' ',$tmp);
        }
        $log = array_column($log,1);
        asort($log);
        $log = array_values($log);
        $log = array_count_values($log);
        asort($log);

        print_r($log);exit;*/
        // 命令的名字（"think" 后面的部分）
        $this->setName('Hello')
            // 配置一个参数 使用$input->getArgument('username')获取
            // ->addArgument('username')
            // 运行 "php think list" 时的简短描述
            ->setDescription('定时任务微服务.')
            // 运行命令时使用 "--help" 选项时的完整命令描述
            ->setHelp("定时任务微服务 无参数");
    }
    /**
     *  * 重写execute
     *  * {@inheritdoc}
     *
     * @param Input $input
     * @param Output $output
     */
    protected function execute(Input $input, Output $output)
    {

        try {
            $result = HttpServer::request('ApiCache',['user_id' => 61,
                'account_id'    => '24038685',
                'access_key'    => '6e37df15-xa2b53ggfc-a023f78c-1aa35',
                'secret_key'    => 'dff7a597-2ee96111-c9c59030-725c4',
                'codes' => 'ethusdt,xrpusdt,adausdt,dotusdt,dogeusdt,uniusdt,ltcusdt,bchusdt,linkusdt,solusdt,filusdt,xlmusdt,trxusdt,eosusdt,aaveusdt,atomusdt,mkrusdt,htusdt,ksmusdt,avaxusdt,compusdt,enjusdt,sushiusdt,nearusdt,zrxusdt,omgusdt,crvusdt,kncusdt,1inchusdt,btcusdt',
                'method'=>'GetHistoryOpenAndClose'],'127.0.0.1:' . HttpServer::serverPort());
        }catch (\Exception $e) {
            echo $e->getMessage();
        }


        print_r($result);exit;
    }

    public function test(){
        static::$redis = Cache::store('redis');

        /* $obj = Cache::store('redis');
         echo '<pre>';
         print_r(count($obj->hgetAll('test')));exit;*/
        echo memory_get_usage() / 1024/1024,'<br />';
        $startTime =  microtime(true);


        try {
            for($j=0;$j<30;++$j) {
                $this->startProcess(function (){
                    for($j=0;$j<20;++$j) {
                        $this->startProcess(function (){
                                $this->select(1);
                        });
                    }
                });
            }

        }catch (\Exception $e) {
            echo $e->getMessage(),'<br />';
        }
        echo microtime(true) - $startTime;
        while ($ret = swoole_process::wait()) {
            $pid = $ret['pid'];

        }
        echo 'end';
        exit;

    }

    public function startProcess($function) {
        $process = new swoole_process(function(swoole_process $worker) use($function){
            try {
                //   file_put_contents(dirname(__FILE__) . '/mysqlGetErr.log',date('Y-m-d H:i:s ') ."\n",FILE_APPEND);

                call_user_func_array($function,[]);
                // file_put_contents(dirname(__FILE__) . '/mysqlGetErr.log',date('Y-m-d H:i:s ') ."\n",FILE_APPEND);
                $worker->exit(0);
            }catch (\Exception $e) {
                //file_put_contents(dirname(__FILE__) . '/mysqlGetErr.log',date('Y-m-d H:i:s ') . $e->getMessage() . "\n",FILE_APPEND);
                $worker->exit(0);
            }
        },false);
        return $process->start();
    }

    public function select($pid)
    {
        $result[] = memory_get_usage() / 1024/1024;

        $result[] =  microtime(true);

        //  Db::startTrans();

        //发布数据
        //   $result = Db::name("sss")->select()->toArray();

        //    $list = Db::query("show status like 'Threads%'");
        //file_get_contents('http://www.jilutie.com');


        /*   foreach($list as $value) {
               switch($value['Variable_name']) {
                   case 'Threads_running':
                       $result['running'] = $value['Value'];
                       break;
                   case 'Threads_connected':
                       $result['connected'] = $value['Value'];
                       break;
               }
           }
           Db::commit();*/



        try {
            //    file_put_contents(dirname(__FILE__) . '/mysqlGet.log',date('Y-m-d H:i:s ') . "\n",FILE_APPEND);

            //$str = static::$redis->hgetAll('test' . rand(100000000,999999999));
            //file_put_contents(dirname(__FILE__) . '/mysqlGet.log',date('Y-m-d H:i:s ') . $pid . ' ' . json_encode($str) . "\n",FILE_APPEND);
         /*   $redis = new Redis();
            $redis->connect('127.0.0.1', 6379);

            $redis->hset('test' . rand(100000000,999999999),rand(100000000,999999999),date('Y-m-d H:i:s ') . implode(',',$result));
            $redis->close();*/
            file_put_contents(dirname(__FILE__) . '/run_times   .log',date('Y-m-d H:i:s ') . (microtime(true) - $result[1]) .  "\n",FILE_APPEND);
        }catch (\Exception $e) {
            $result[] =  microtime(true);
            array_unshift($result,$result[2] - $result[1]);
            file_put_contents(dirname(__FILE__) . '/mysql.log',date('Y-m-d H:i:s ') . $pid . ' ' . $e->getMessage() . ' ' . implode(',',$result) . "\n",FILE_APPEND);
        }

    }
}